﻿using CSRedis;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GuanYijia.Application
{
    public class RedisHelper
    {
        private static CSRedisClient redisClient;

        /// <summary>
        /// 第一次被访问的时候会调用静态构造函数，有且仅有一次
        /// </summary>
         static RedisHelper()
        {
            //redisClient = new CSRedisClient("172.21.130.178:8001");
            redisClient = new CSRedisClient("localhost:6379");
        }

        /// <summary>
        /// 不带过期时间的set
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="data"></param>
        public static void Set<T>(string key, T data)
        {
            redisClient.Set(key, JsonConvert.SerializeObject(data));
        }

        /// <summary>
        /// 带过期时间的set
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="data"></param>
        /// <param name="expireTime"></param>
        public static void Set<T>(string key, T data, TimeSpan expireTime)
        {
            redisClient.Set(key, JsonConvert.SerializeObject(data), expireTime);
        }

        /// <summary>
        /// 查询redis里是否有传过来的key
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public static T Get<T>(string key)
        {
            var data = redisClient.Get(key);

            if (data == null)
            {
                return default;
            }

            return JsonConvert.DeserializeObject<T>(data)!;
        }

        /// <summary>
        /// 删除redis中传来的key
        /// </summary>
        /// <param name="key"></param>
        public static void Remove(string key)
        {
            redisClient.Del(key);
        }
    }
}
